package demo7;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.net.Socket;

@Component
@PropertySource("classpath:config.properties")
public class Client implements InitializingBean, DisposableBean {
    private Socket socket;
    private String url;
    private int port;

    @Override
    public String toString() {
        return "Client{" +
                "port=" + port +
                ", socket=" + socket +
                ", url='" + url + '\'' +
                '}';
    }

    public int getPort() {
        return port;
    }

    @Value("${8808}")
    public void setPort(int port) {
        this.port = port;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getUrl() {
        return url;
    }

    @Value("${localhost}")
    public void setUrl(String url) {
        this.url = url;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("正在初始化服务器");
        socket = new Socket(url,port);
        System.out.println("已连接服务器");
    }

    @Override
    public void destroy() throws Exception {
        socket.close();
    }
}
